//
//  EmotionTool.m
//  微博2期
//
//  Created by J on 15/12/20.
//
//


//存储路径
#define RecentEmotionsPath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"emotions.archive"]
#import "EmotionTool.h"
#import "Emotion.h"
@implementation EmotionTool

static  NSMutableArray * _recentEmotions;

+ (void)initialize{//第一次使用这个类的时候调用一次  之后不会调用
    _recentEmotions = [NSKeyedUnarchiver unarchiveObjectWithFile:RecentEmotionsPath];
    if (!_recentEmotions) {
        //        NSLog(@"!emotions!emotions");
        _recentEmotions = [NSMutableArray array];
    }
}
+ (Emotion*)emotionWithChs:(NSString*)chs{//遍历最近和emoji
    
    for (Emotion* emotion in [self defaultEmotions]) {
        if ([emotion.chs isEqualToString:chs]) return emotion;
    }
    
    for (Emotion* emotion in [self lxhEmotions]) {
        if ([emotion.chs isEqualToString:chs]) return emotion;
    }
    
    return  nil;
}


static NSArray* _emojiEmotions,*_defaultEmotions,*_lxhEmotions;


+ (NSArray *)defaultEmotions{
    
    if (!_defaultEmotions) {
       _defaultEmotions = [self emotionWithPath:@"EmotionIcons/default/info.plist"];
    }

    return _defaultEmotions;
}

+ (NSArray*)lxhEmotions{
    
    if (!_lxhEmotions) {
        _lxhEmotions = [self emotionWithPath:@"EmotionIcons/lxh/info.plist"];
    }
    return _lxhEmotions;
    
}

+ (NSArray*)emojiEmotions{
    if (!_emojiEmotions) {
        _emojiEmotions = [self emotionWithPath:@"EmotionIcons/lxh/info.plist"];
    }
    return _emojiEmotions;
 }

+ (NSArray*)emotionWithPath:(NSString*)path{
    NSString* emojiPath = [[NSBundle mainBundle]pathForResource:path ofType:nil];
    NSArray* defaultEmotions =  [Emotion objectArrayWithKeyValuesArray:[NSArray arrayWithContentsOfFile:emojiPath]];
    return defaultEmotions;
}

+ (void)addRecentEmotion:(Emotion*)emotion{
    [_recentEmotions removeObject:emotion];
    [_recentEmotions insertObject:emotion atIndex:0];//将表情放到数组最前面
    //将所有的表情数据写入沙盒
    [NSKeyedArchiver archiveRootObject:_recentEmotions toFile:RecentEmotionsPath];
}


//返回装着Emotion模型的数组
+ (NSArray*)recentEmotions{
    return _recentEmotions;
}


//删除重复表情
//1.
//    for (NSUInteger i=0; i<emotions.count; i++) {
//        Emotion * e = emotions[i];
//        if ([e.chs isEqualToString:emotion.chs]||[e.code isEqualToString:emotion.code]) {
//            [emotions removeObject:e];
//            break;
//        }
//    }
//2.
//    for (Emotion * e in emotions) {
//        if ([e.chs isEqualToString:emotion.chs]||[e.code isEqualToString:emotion.code]) {
//                [emotions removeObject:e];
//                break;
//            }
//    }


@end
